//
//  tdl/sys/process.h
//  Created by tommywang on 13/04/27.
//

#ifndef tdl_sys_process_h
#define tdl_sys_process_h
#include <signal.h>
#include <sys/stat.h>

namespace tdl {
////////////////////
void daemon()
{
	pid_t pid;
	struct sigaction sig;

	if((pid = ::fork()) != 0)
		::exit(0);

	::setsid();
	::signal(SIGHUP, SIG_IGN);
	::signal(SIGQUIT, SIG_IGN);
	::signal(SIGPIPE, SIG_IGN);
	::signal(SIGTTOU, SIG_IGN);
	::signal(SIGTTIN, SIG_IGN);
	::signal(SIGCHLD, SIG_IGN);
	::signal(SIGTERM, SIG_IGN);
	/* This ignores the SIGPIPE signal.  This is usually a good idea, since
	   the default behaviour is to terminate the application.  SIGPIPE is
	   sent when you try to write to an unconnected socket. */
	sig.sa_handler = SIG_IGN;
	sig.sa_flags = 0;
	sigemptyset(&sig.sa_mask);
	::sigaction(SIGPIPE, &sig, NULL);

	if((pid = ::fork()) != 0)
		::exit(0);

	::umask(0);
}

//////////////////
} // namespace tdl

#endif

